package me.hgj.jetpackmvvm.ledun.ui.fragment.home

import android.Manifest
import android.app.ProgressDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothGattCharacteristic
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.BleLog
import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback
import cn.com.heaton.blelibrary.ble.model.BleDevice
import cn.com.heaton.blelibrary.ble.utils.ByteUtils

import com.zhpan.bannerview.BannerViewPager
import kotlinx.android.synthetic.main.fragment_home.device_recyclerView
import kotlinx.android.synthetic.main.fragment_home.iv_device
import kotlinx.android.synthetic.main.fragment_home.tv_bl_state
import kotlinx.android.synthetic.main.fragment_home.tv_device_name
import kotlinx.android.synthetic.main.include_list.*
import kotlinx.android.synthetic.main.include_recyclerview.*
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ledun.R
import me.hgj.jetpackmvvm.ledun.app.appViewModel
import me.hgj.jetpackmvvm.ledun.app.base.BaseFragment1
import me.hgj.jetpackmvvm.ledun.app.eventViewModel
import me.hgj.jetpackmvvm.ledun.app.ext.*
import me.hgj.jetpackmvvm.ledun.app.weight.banner.HomeBannerAdapter
import me.hgj.jetpackmvvm.ledun.app.weight.banner.HomeBannerViewHolder
import me.hgj.jetpackmvvm.ledun.app.weight.recyclerview.DefineLoadMoreView
import me.hgj.jetpackmvvm.ledun.app.weight.recyclerview.SpaceItemDecoration
import me.hgj.jetpackmvvm.ledun.data.model.bean.BannerResponse
import me.hgj.jetpackmvvm.ledun.data.model.bean.CollectBus
import me.hgj.jetpackmvvm.ledun.databinding.FragmentHomeBinding
import me.hgj.jetpackmvvm.ledun.ui.adapter.AriticleAdapter
import me.hgj.jetpackmvvm.ledun.ui.adapter.DeviceAdapter
import me.hgj.jetpackmvvm.ledun.viewmodel.request.RequestCollectViewModel
import me.hgj.jetpackmvvm.ledun.viewmodel.request.RequestHomeViewModel
import me.hgj.jetpackmvvm.ledun.viewmodel.state.HomeViewModel

import me.hgj.jetpackmvvm.ledun.viewmodel.state.MainViewModel
import me.hgj.jetpackmvvm.util.ActivityMessenger.finish
import java.util.UUID

/**
 * 作者　: hegaojian
 * 时间　: 2019/12/27
 * 描述　:
 */
class HomeFragment : BaseFragment1<HomeViewModel, FragmentHomeBinding>() {

    private  var mBle: Ble<BleDevice> = Ble.getInstance()  //获取到这个单列。。
    private var listDatas = mutableListOf<BleDevice>()
    private val adapter = DeviceAdapter(listDatas)
    private lateinit var atViewModel: MainViewModel
    private var dialog: ProgressDialog?= null
    private  var isNotInit:Boolean=true
    override fun initView(savedInstanceState: Bundle?) {
        //状态页配置
        atViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
        //初始化
        mViewBind.includeToolbar.toolbar.run {
            init("蓝牙连接")

        }
        device_recyclerView.layoutManager = LinearLayoutManager(activity)
        device_recyclerView.adapter = adapter
        adapter.setOnItemClickListener {
            val device = adapter.items[it]
            device.apply {
                if (isConnected){
                    mBle.disconnect(this)
                }else if (!isConnecting){
                    mBle.connect(this, connectCallback())
                }
            }
        }


    }
    private fun connectCallback(): BleConnectCallback<BleDevice> {
        return object : BleConnectCallback<BleDevice>(){
            override fun onConnectionChanged(device: BleDevice?) {
                adapter.notifyDataSetChanged()
            }

            override fun onReady(device: BleDevice?) {
                super.onReady(device)
                Log.e("laiyiwen", "onReady: ...${device?.bleName}")
                mBle.enableNotify(device, true, bleNotifyCallback())
//                iv_device.setImageResource(R.mipmap.light_on)
//                tv_device_name.text="设备号：${device?.bleName}"
//                tv_bl_state.text="状态：已连接"
            }

        }
    }

    private fun bleNotifyCallback(): BleNotifyCallback<BleDevice> {
        return object : BleNotifyCallback<BleDevice>(){
            override fun onChanged(device: BleDevice?, characteristic: BluetoothGattCharacteristic?) {
                Log.e("laiyiwen", ByteUtils.toHexString(characteristic?.value))
            }

            override fun onNotifySuccess(device: BleDevice?) {
                super.onNotifySuccess(device)

                Log.e("laiyiwen", "设置通知成功:"+device?.bleName)
            }
        }
    }



    /**
     * 懒加载
     */
    override fun lazyLoadData() {
        //设置界面 加载中
    }

    override fun createObserver() {

        atViewModel.sharedData.observe(viewLifecycleOwner, Observer {
            Log.e("laiyiwen", "createObserver: $it" )
            adapter.items=it
            adapter.notifyDataSetChanged()
        })
    }




}